package com.blacktech.dbu.auth.controller;

import com.blacktech.dbu.auth.dto.CreateUserRequest;
import com.blacktech.dbu.auth.dto.UpdateUserRequest;
import com.blacktech.dbu.auth.entity.DbuUser;
import com.blacktech.dbu.auth.security.RolePermission;
import com.blacktech.dbu.auth.service.AuthenticationService;
import com.blacktech.dbu.auth.service.UserService;
import com.blacktech.dbu.core.dict.UserStatus;
import com.blacktech.dbu.core.dict.UserType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 *
 * @author Yanyunsong
 */
@RestController
@RequestMapping("/api/users")
@RolePermission(required = UserType.Level.ADMIN)
@Tag(name = "用户管理", description = "用户信息管理相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationService authenticationService;

    @GetMapping("/all")
    @Operation(summary = "获取所有用户", description = "获取所有用户列表（用于下拉选择）")
    public List<DbuUser> getAllUsers() {
        List<DbuUser> users = userService.findAllUsers();
        // 清除敏感信息
        users.forEach(user -> user.setPassword(null));
        return users;
    }

    @GetMapping
    @Operation(summary = "获取用户列表", description = "分页查询用户列表")
    public Page<DbuUser> getUsers(
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "显示名称") @RequestParam(required = false) String displayName,
            @Parameter(description = "用户类型") @RequestParam(required = false) UserType userType,
            @Parameter(description = "用户状态") @RequestParam(required = false) UserStatus status,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createTime") String sort,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "desc") String direction) {

        Sort.Direction sortDirection = "asc".equalsIgnoreCase(direction) ?
                Sort.Direction.ASC : Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));

        Page<DbuUser> users = userService.findUsers(username, displayName, userType, status, pageable);
        // 清除敏感信息
        users.getContent().forEach(user -> user.setPassword(null));
        return users;
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据ID获取用户详细信息")
    public DbuUser getUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        DbuUser user = userService.getUserById(id);
        // 清除敏感信息
        user.setPassword(null);
        return user;
    }

    @GetMapping("/current")
    @PreAuthorize("isAuthenticated()")  // 只需要已登录，不需要管理员权限
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    public DbuUser getCurrentUser() {
        DbuUser currentUser = authenticationService.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("当前用户不存在");
        }
        // 清除敏感信息
        currentUser.setPassword(null);
        return currentUser;
    }

    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public DbuUser createUser(@Valid @RequestBody CreateUserRequest request) {
        // 获取当前操作用户ID
        Long operatorId = authenticationService.getCurrentUserId();

        // 如果是第一个用户，自动设为超级管理员
        if (userService.isFirstUser()) {
            request.setUserType(UserType.SUPER_ADMIN);
        }

        DbuUser user = userService.createUser(request, operatorId);
        // 清除敏感信息
        user.setPassword(null);
        return user;
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public DbuUser updateUser(
            @Parameter(description = "用户ID") @PathVariable Long id,
            @Valid @RequestBody UpdateUserRequest request) {

        Long operatorId = authenticationService.getCurrentUserId();
        DbuUser user = userService.updateUser(id, request, operatorId);
        // 清除敏感信息
        user.setPassword(null);
        return user;
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "删除指定用户")
    public void deleteUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        Long operatorId = authenticationService.getCurrentUserId();
        userService.deleteUser(id, operatorId);
    }

    @PostMapping("/{id}/reset-password")
    @Operation(summary = "重置密码", description = "重置用户密码，返回临时密码")
    public Map<String, String> resetPassword(@Parameter(description = "用户ID") @PathVariable Long id) {
        Long operatorId = authenticationService.getCurrentUserId();
        String tempPassword = userService.resetPassword(id, operatorId);

        Map<String, String> result = new HashMap<>();
        result.put("temporaryPassword", tempPassword);
        return result;
    }

    @PostMapping("/{id}/toggle-status")
    @Operation(summary = "切换用户状态", description = "启用或禁用用户")
    public void toggleUserStatus(@Parameter(description = "用户ID") @PathVariable Long id) {
        Long operatorId = authenticationService.getCurrentUserId();
        userService.toggleUserStatus(id, operatorId);
    }

    @PostMapping("/{id}/lock")
    @Operation(summary = "锁定用户", description = "锁定用户账户")
    public void lockUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        Long operatorId = authenticationService.getCurrentUserId();
        userService.lockUser(id, operatorId);
    }

    @PostMapping("/{id}/unlock")
    @Operation(summary = "解锁用户", description = "解锁用户账户")
    public void unlockUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        Long operatorId = authenticationService.getCurrentUserId();
        userService.unlockUser(id, operatorId);
    }

    @GetMapping("/admins")
    @RolePermission(required = UserType.Level.SUPER_ADMIN)
    @Operation(summary = "获取超级管理员列表", description = "获取所有超级管理员用户")
    public List<DbuUser> getSuperAdmins() {
        List<DbuUser> admins = userService.getSuperAdmins();
        // 清除敏感信息
        admins.forEach(admin -> admin.setPassword(null));
        return admins;
    }
}